var dataAll = [];
var filterCategoty = "";
var filterName = "";
var filterStatus = 0
$(document).ready(function() {
	update();
	
	
	
	var user =JSON.parse(localStorage.getItem("currentUser"));
	if (user.role == 3) {
		$(".common_user_operate").addClass("user_hide");
	} else if (user.role == 2) {
		console.log("-----------");
		$(".warehouse-select-html").addClass("warehouse-select");
	}
	
	//查询
	$(".searchbtn").click(function(){
		filterStatus = $("#status").val();
		filterCategoty = $("#type").val();
		filterName = $("#name").val();
		update();
	})
	
	//是否报废？
	$(".deahBtn").click(function(){
		var data = JSON.parse($(this).attr("dataRow"))
		console.log($(this).attr("dataRow"));
		updateAppliance(data.id, 3, function(isSuccess) {
			if (isSuccess) {
				update();
			}
		})
	})
	
	//借出 1:库内、2：库外、3：报废
	$(".borrowBtn").click(function(){
		var data = JSON.parse($(this).attr("dataRow"))
		console.log($(this).attr("dataRow"));
		updateAppliance(data.id, 2, function(isSuccess) {
			if (isSuccess) {
				update();
			}
		})
		var userJson = localStorage.getItem("currentUser");
		var user = JSON.parse(userJson);
		
		var date = new Date();
		var month = parseInt(date.getMonth()) + 1 ;
		month = month > 9 ? month: '0' + month ;
		
		var day = parseInt(date.getDate()) + 1;
		day = day > 9 ? day: '0' + day ;
		
		var detailTime = date.getFullYear() + "-" + month + "-" + day;
		addBorrow(data.warehouse, data.warehouseId, data.id, data.category, data.name, 2, detailTime, user.name, user.id);
	})
	
	$(".save").click(function(){
		var catetory = $("#seris").val();
		var name = $("#applName").val();
		var date = $("#intoDate").val();
		var status = $("#status2").val();
		var ware = ($("#kuStatus").val()).split("$");
		console.log(status + "--------");
		if(!catetory){
			alert("请输入类别")
			return
		}
		if(!name){
			alert("请输入名称")
			return
		}
		if(!date){
			alert("请选择日期")
			return
		}
		if(!status){
			alert("请选择状态")
			return
		}
		if(!$("#kuStatus").val()){
			alert("请选择库房")
			return
		}
		if(ware.length < 2) {
			alert("数据出错，请稍后再试！");
			return;
		}
		var wareId = ware[0];
		var wareName = ware[1];
		$(this).attr("data-dismiss", "modal");	
		addAppliance(catetory, name, date, status, wareName, wareId, function(success){
			if(success){
				alert("新增成功！");
				$("#seris").val("");
				$("#applName").val("");
				$("#intoDate").val("");
				$("#status2").val("");
				$("#kuStatus").val("");
				update();
				return
			}
		});
	})
	
	// 获取仓库列表
	getWarehouseList(function(list) {
		var wareHtml = '<option value="">请选择</option>';
		for(var i=0; i<list.length; i++){
			wareHtml += '<option value="'+list.item(i).id+"$"+list.item(i).name+'">'+list.item(i).name+'</option>'
		}
		$("#kuStatus").html(wareHtml)
	});
})

function update() {
	dataAll = []
	if (filterStatus > 0 || filterCategoty.length > 0 || filterName.length > 0) {
		getAppliancListFilterCategory(filterCategoty, filterName, filterStatus, function(list) {
			dealWithData(list);
			console.log(list);
		});
	} else {
		getAppliancList(function(list) {
			dealWithData(list);
		});
	}	
}

function dealWithData(list) {
	var user =JSON.parse(localStorage.getItem("currentUser"));
	for(var i=0; i<list.length; i++){
		if (user.role == 1) {
			dataAll.push(list.item(i));
		} else {
			if (user.warehouseId == list.item(i).warehouseId) {
				dataAll.push(list.item(i));
			}
		}
	}
	ss();
}

function ss(){
	$('#tab').bootstrapTable({pageNo:1});
	search();
}
var page;
function checkData(date) {
	console.log("22");
	 page={
			rows:date.data,
			total:date.total
		}	
	return page;
}
// 加载所有工器具信息
function search() {	
	$('#tab').bootstrapTable('destroy');
	$('#tab').bootstrapTable({
		data:dataAll,
		// strictSearch:true,
		// striped:true,// 是否显示行间隔色
		// search:true,
		pagination:true,// 是否显示分页（*）
		pageSize:10,// 每页的记录行数（*）
		pageNumber:1,// 初始化加载第一页，默认第一页
		sortable:true,// 是否启用排序
		sortName:"addTime",
		sortOrder:"desc",// 排序方式
		columns: [{
			field:'check',
			valign:'middle',
			align:'center',
			checkbox: true
		},{
			field:'category',
			title:'类别',
			valign:'middle',
			align:'center'
		}, {
			field:'name',
			title:'名称',
			valign:'middle',
			align:'center'
		}, {
			field:'addTime',
			title: '入库时间',
			valign:'middle',
			align:'center',
			sortable:true
		}, {
			field: 'status',
			title: '状态',
			align: 'center',
			valign: 'middle',
			align:'center',
			formatter: statusFormatter
		}, {
			field : 'warehouse',
			title : '库房',
			align : 'center',
			valign : 'middle'
		}, {
			field : 'operate',
			title : '操作',
			valign : 'middle',
			align:'center',
			formatter : operateFormatter,
			events : operateEvents
		} ],
		onLoadSuccess : function(data) {			
			
		},
		onLoadError : function() {
			// location.reload();
		}
	});
}
// 得到查询的参数
var sn;
var so;
function queryParams(params) {
};
/*
系统管理员： 在库内显示"待报废"
库管理员： 在库内显示"借出"、"待报废"
成员： 在库内显示"借出"
*/
function operateFormatter(value, row, index) {
	role = JSON.parse(localStorage.getItem("currentUser"));
	if(row.status == 1 && role.role == 1){
		return [
				'<a class="death btn btn-sm btn-info" href="javascript:void(0)" title="details">报废</a>',
				].join('');
	}else if(row.status == 1 && role.role == 2){
		return [
		        '<a class="borrow btn btn-sm btn-info" href="javascript:void(0)" title="details">借出</a>&nbsp&nbsp',
				'<a class="death btn btn-sm btn-info" href="javascript:void(0)" title="details">报废</a>',
				].join('');
	} else if(row.status == 1 && role.role == 3){
		return [
		        '<a class="borrow btn btn-sm btn-info" href="javascript:void(0)" title="details">借出</a>&nbsp&nbsp',
				].join('');
	}	
}
window.operateEvents = {// 显示修改
	'click .borrow' : function(e, value, row, index) {
		$(".borrowBtn").attr("dataRow",JSON.stringify(row));
		$('#impload').click();
	},
	'click .death' : function(e, value, row, index) {
		// console.log(row)
		$(".deahBtn").attr("dataRow",JSON.stringify(row));
		$('#imdeath').click();
	}
}

$(function() {	
	$("button.one").click(function() {
		var cookieval = readCookie("operateID");
		var data = {
			'operatorID' : cookieval,
			'carID' : $("#control_table").attr("data-id"),
			'controlType' : $(this).val()
		};
	})
})
// 入库状态
function statusFormatter(value, row, index) {
	value = parseInt(value);
	var status;
	switch (value) {
	case 1:
		status = '库内';
		break;
	case 2:
		status = '库外';
		break;
	case 3:
		status = '报废';
		break;
	default:
		status = '';
		break;
	}
	return status;
}
